import path from "node:path";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import viteCompression from "vite-plugin-compression";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Pages from "vite-plugin-pages";

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd()); // 获取 .env里面定义是参数
  return {
    base: "./",
    server: {
      port: 8089,
      host: "0.0.0.0",
      proxy: {
        "^/roomManage": {
          target: env.VITE_APP_BASE_URL, // 后端服务实际地址
          changeOrigin: true //开启代理
        }
      }
    },
    resolve: {
      alias: {
        "@": path.resolve(process.cwd(), "src"),
        "~": path.resolve(process.cwd(), "src")
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: "modern-compiler",
          silenceDeprecations: ["legacy-js-api"],
          additionalData: `@use "@/assets/css/element.scss" as *;`
        }
      }
    },
    plugins: [
      vue(),
      Pages({
        dirs: "src/pages", // 需要生成路由的文件目录，默认就是识别src下面的pages文件
        exclude: ["**/components/*.vue"] // 排除在外的目录，上面配置目录的例子，里面有 components 目录，我们不希望他被解析为路由
      }),
      AutoImport({
        imports: ["vue", "vue-router"],
        dts: "src/auto-imports.d.ts", // 自动生成的 TypeScript 类型声明文件
        eslintrc: {
          enabled: true, // 启用 ESLint 支持
          filepath: "./.eslintrc-auto-import.json",
          globalsPropValue: true
        },
        resolvers: [ElementPlusResolver({ importStyle: "sass" })]
      }),
      Components({
        resolvers: [ElementPlusResolver({ importStyle: "sass" })]
      }),
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: "gzip",
        ext: ".gz"
      })
    ],
    build: {
      target: "es2015",
      minify: "terser",
      chunkSizeWarningLimit: 1500,
      cssCodeSplit: true, //css 拆分
      sourcemap: false, //不生成sourcemap
      terserOptions: {
        compress: {
          //生产环境时移除console
          drop_console: true,
          drop_debugger: true
        }
      },
      rollupOptions: {
        output: {
          format: "es",
          compact: false,
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id.toString().split("node_modules/")[1].split("/")[0].toString();
            }
          },
          chunkFileNames: chunkInfo => {
            const facadeModuleId = chunkInfo.facadeModuleId
              ? chunkInfo.facadeModuleId.split("/")
              : [];
            const fileName = facadeModuleId[facadeModuleId.length - 2] || "[name]";
            return `js/${fileName}/[name].[hash].js`;
          }
        }
      },
      assetsInlineLimit: 5000
    }
  };
});
